'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	const filter = {
		uid: event.uid
	};
	if (event.type == 'setting') { // 我的个人资料修改
		let res = await db.collection('user-table').doc(event._id).update({
			avatar: event.avatar,
			name: event.name,
			sex: event.sex,
			age: event.age,
			Introduction: event.Introduction, // 简介
			bgImg: event.bgImg
		})

		// console.log(JSON.stringify(res));
		
		// 修改完个人资料后，memory-pool表中的用户资料一同更新
		// let dataList = await db.collection('memor-pool').where(filter).get();
		// // console.log(dataList);
		// dataList.data.forEach((item,index)=>{  // 循环修改列表
		// 	let res = db.collection('memor-pool').doc(item._id).update({
		// 		avatar: event.avatar,
		// 		name: event.name
		// 	})
		// })

		return {
			code: 0,
			msg: '修改成功',
			data: res
		}
	} else {
		// 登录创建用户 无创建，有跳过
		// let len = await db.collection(event.tableName).where(filter).count();
		let data = await db.collection(event.tableName).where(filter).get();
		// console.log(data)
		// console.log(len);
		// if (len.total == 0) {
		if (data.data.length == 0) {
			const collection = db.collection(event.tableName)
			const res = await collection.add(event)
			return {
				code: 0,
				msg: '创建新用户',
				data: event
			}
		} else {
			return {
				code: 1,
				msg: '已拥有此用户',
				data: data.data[0]
			}
		}
	}
};
